let Paho = require('./paho-mqtt.js');
var mqtt = {};
//client对象
var client = null;
//mqtt连接对象
const mqttUrl = {
    hostname: "wss://mk-iot.com/mqttwss",
    // port:8084,
    // path: "/mqtt"
}

//订阅的主题与回掉方法
var map = new Map();

/**
 * mqtt 连接状态
 * 0:正在连接
 * 1:连接成功建立
 * 2:连接正在关闭
 * 3:连接已经关闭
 */
let connectStatus = 0;

//初始化weboscket
mqtt.initMqtt = (equipmentNo) => {
    if (null == client) {
        //创建mqtt客户端
        client = new Paho.Client(mqttUrl.hostname, "SERVER_" + Math.floor(Math.random() * 999) + 1 + "_" + equipmentNo);
    }

    client.onConnected = (reconnect, uri) => {
        console.log("mqtt连接成功！client：", reconnect, uri);
        //连接成功
        connectStatus = 1;
        //注册全局的报警事件
    }

    client.onConnectionLost = (responseObject) => {
        console.log("mqtt连接关闭！", responseObject);
        if (responseObject.errorCode != 0) {
            //异常关闭
            mqtt.initMqtt();
        } else {
            //正常关闭连接
        }
        connectStatus = 3;
    }

    client.onMessageArrived = (message) => {
        //console.log("Message Recieved: [Topic: ", message.destinationName, ", Payload: ", message.payloadString, ", QoS: ", message.qos, ", Retained: ", message.retained, ", Duplicate: ", message.duplicate, "]");
        let topic = message.destinationName;
        //console.log("map:",map);
        try {
            let msgObj = {}
            new Promise((resolve, reject) => {/* executor函数 */
                return resolve(message.payloadString);
            }).catch(function (value) {
                console.log('JSON转化异常')
                return;
            });
            if (topic.indexOf('$SYS/brokers/') > -1) {
                map.get('home')(topic, msgObj);
            } else if (topic.indexOf('/client') > -1) {
                map.get('device')(topic, msgObj);
            } else {
                map.get('msg')(topic, msgObj);
            }
        } catch (err) {
            console.error(err);
        }

    }


    var options = {
        invocationContext: {
            host: mqttUrl.hostname,
            // port: mqttUrl.port,
            // path: mqttUrl.path,
            // clientId: 'uniapp_client_'+Math.random(),
        },
        //超时
        timeout: 5,
        //心跳
        keepAliveInterval: 60,
        //清除session，如果不清除，重连之后还能收到订阅的数据
        cleanSession: true,
        useSSL: true,
        reconnect: true,
        userName: "test",
        password: "root",
        onSuccess: onConnect,
        onFailure: onFail
    };

    function onConnect(context) {
        console.log("mqtt连接成功context：", context)
        //连接成功
        connectStatus = 1;
    }

    function onFail(context) {
        console.log("mqtt连接失败onFail：", context)
        mqtt.initMqtt();
    }

    if (1 != connectStatus) {
        console.log("开始连接");
        client.connect(options);
        //正在建立连接
        connectStatus = 0;
    }


}


/**
 * 订阅主题
 * topic：主题名称
 * qos：服务质量
 */
mqtt.subscribe = function (topic, qos, receiveCallback) {
    if (1 == mqtt.getStatus()) {
        client.subscribe(topic, {
            qos: Number(qos)
        });
        if (topic.indexOf('$SYS/brokers/') > -1) {
            map.set('home', receiveCallback);
        } else if (topic.indexOf('/client') > -1) {
            map.set('device', receiveCallback);
        } else {
            map.set('msg', receiveCallback);
        }
    } else {
        setTimeout(function () {
            mqtt.subscribe(topic, qos, receiveCallback);
        }, 1000)
    }
}

/**
 * 取消订阅主题
 * topic：主题名称
 */
mqtt.unsubscribe = function (topic) {
    if (1 == mqtt.getStatus()) {
        client.unsubscribe(topic, {
            onSuccess: unsubscribeSuccess,
            onFailure: unsubscribeFailure,
            invocationContext: {
                topic: topic
            }
        });
        map.delete(topic);
    } else {
        setTimeout(function () {
            mqtt.unsubscribe(topic);
        }, 1000)
    }
}

function unsubscribeSuccess(context) {
    console.log("取消订阅成功Topic：", context.invocationContext.topic);
}

function unsubscribeFailure(context) {
    console.log("取消订阅成功Topic：", context.invocationContext.topic);
    setTimeout(function () {
        mqtt.unsubscribe(context.invocationContext.topic);
    }, 1000)
}

/**
 * 发送消息
 * message：消息内容
 * topic：主题
 * qos：服务质量
 */
mqtt.publish = function (message, topic, qos) {
    if (1 == mqtt.getStatus()) {
        var message = new Paho.Message(message);
        message.destinationName = topic;
        message.qos = Number(qos);
        message.retained = false;
        client.send(message);
        uni.showToast({
            title: '发送成功'
        })
    } else {
        uni.showToast({
            title: '正在重新连接服务器，请稍后重试',
            icon: 'none',
            duration: 2000
        })
        setTimeout(function () {
            mqtt.publish(message, topic, qos);
        }, 1000)
    }
}


/**
 * 返回mqtt的连接状态
 */
mqtt.getStatus = function () {
    return connectStatus;
}



/**
 * 关闭连接
 */
mqtt.disconnect = function () {
    console.log("关闭mqtt连接");
    if (null != client) {
        client.disconnect();
    } else {
        //Do-nothing
    }
    connectStatus = 3;
    client = null;
}

mqtt.initMqtt();

export default mqtt;